import { SELECT_ARTICLE_DATA, FETCH_ARTICLE_DATA, INIT_SEL_ARTICLE_DATA, FETCH_APPROVE_DATA, RESOLVE_APPROVE_DATA, REJECT_APPROVE_DATA, FETCH_APPROVE_LIST} from '../actions/article';

const INITIAL_STATE = { articles: [], page: 1 ,approvel:[]};

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case SELECT_ARTICLE_DATA:
            if ((action.payload && action.payload.data && action.payload.data.page && action.payload.data.page === 1)
                || action.payload.status != 200 || action.payload.data.articles == undefined) {
                state.articles = [];
                state.page = 1;
                state.pageCount = 1;
            }
            if (action.payload && action.payload.data && action.payload.data.articles && action.payload.data.articles.length > 0) {
                state.articles = action.payload.data.articles;
                state.page = action.payload.data.page;
                state.pageCount = action.payload.data.pageCount;
            }
            
            return { ...state };
        case FETCH_ARTICLE_DATA:
            if (action.payload && action.payload.data && action.payload.data.articles && action.payload.data.length > 0) {
                if (state && state.articles) {
                    state.articles = state.articles.concat(action.payload.data);
                    state.page = action.payload.data.page;
                    state.pageCount = action.payload.data.pageCount;
                } else {
                    state.articles = action.payload.data;
                    state.page = action.payload.data.page;
                    state.pageCount = action.payload.data.pageCount;
                }
            }
            return { ...state };
        case INIT_SEL_ARTICLE_DATA:
            state.articles = [];
            state.page = 1;
            state.pageCount = 0;
            return { ...state };
        case FETCH_APPROVE_DATA:
            return { ...state, article: action.payload.data.article};
        case FETCH_APPROVE_LIST:
            return { ...state, approvel: action.payload.data }
        default:
            return state;
    }
}

